import json
import os
from datetime import datetime
import re

def load_questions():
    """加载合并后的题目库"""
    with open('tiku/merged_questions.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    return data['questions']

def load_progress():
    """加载进度记录"""
    progress_file = 'quiz_progress.txt'
    if os.path.exists(progress_file):
        with open(progress_file, 'r', encoding='utf-8') as f:
            content = f.read().strip()
            if content:
                return int(content)
    return 0

def save_progress(last_index):
    """保存进度记录"""
    with open('quiz_progress.txt', 'w', encoding='utf-8') as f:
        f.write(str(last_index))

def parse_question_for_html(question_text):
    """
    为HTML显示解析题目内容
    """
    # 直接使用原始题目文本
    return question_text

def escape_json_string(s):
    """转义JSON字符串中的特殊字符"""
    if not isinstance(s, str):
        s = str(s)
    return s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t')

def extract_options(question_text):
    """
    从题目文本中提取选项
    """
    options = []
    
    # 查找选项部分 - 更准确的匹配
    options_section = re.search(r'[**#]*\s*选项[**#]*[：:]*\s*([A-D][\s\S]*?)(?=\s*[**#]*\s*(?:答案与解析|正确答案))', question_text, re.DOTALL)
    
    if options_section:
        options_text = options_section.group(1)
        
        # 为每个选项提取内容 - 使用更精确的正则表达式
        for i in range(4):  # A, B, C, D四个选项
            option_char = chr(65 + i)
            
            # 匹配选项格式，例如 "A. 选项内容" 或 "A、选项内容"
            option_pattern = f'{option_char}[\\.、]\\s*([^\n]*?)(?=\\s*[B-E][\\.、]|\\s*$|\\s*\\*\\*答案与解析|\\s*正确答案)'
            option_match = re.search(option_pattern, options_text, re.DOTALL)
            
            if option_match:
                option_text = option_match.group(1).strip()
                # 移除多余的空白字符
                option_text = re.sub(r'\s+', ' ', option_text)
                options.append(option_text)
            else:
                # 备用匹配方式
                option_pattern2 = f'{option_char}\\s*[\\.、]\\s*([^\n]*)'
                option_match2 = re.search(option_pattern2, options_text)
                if option_match2:
                    option_text = option_match2.group(1).strip()
                    option_text = re.sub(r'\s+', ' ', option_text)
                    options.append(option_text)
                else:
                    options.append(f"选项{option_char}")
    else:
        # 如果没有找到选项部分，使用默认选项
        for i in range(4):
            options.append(f"默认选项{chr(65 + i)}")
    
    # 确保有4个选项
    while len(options) < 4:
        options.append(f"补充选项{chr(65 + len(options))}")
    
    return options[:4]  # 确保只有4个选项

def extract_answer(question_text):
    """
    从题目文本中提取答案
    """
    answer_match = re.search(r'正确答案[：:]\s*([A-D])', question_text)
    return answer_match.group(1) if answer_match else 'A'

def extract_explanation(question_text):
    """
    从题目文本中提取解析
    """
    # 尝试多种模式提取解析
    explanation_patterns = [
        r'解析[：:]\s*([^\n]*)',
        r'正确答案[：:]\s*[A-D]\s*\n\s*([\s\S]*?)(?=\n\s*[A-D]\.|$)',
        r'正确答案[：:]\s*[A-D]\s*\n*\s*([^\n]*)',
        r'解析[：:]\s*([\s\S]*?)(?=\n\s*[A-D]\.|$)'
    ]
    
    explanation = ""
    for pattern in explanation_patterns:
        explanation_match = re.search(pattern, question_text)
        if explanation_match:
            explanation = explanation_match.group(1).strip()
            # 如果解析太短，可能是错误匹配，继续尝试
            if len(explanation) > 10:
                break
    
    return explanation

def generate_quiz_html(questions):
    """生成测验HTML文件"""
    # 构造题目数据
    quiz_items = []
    for i, q in enumerate(questions):
        # 提取题目各部分信息
        question_text = parse_question_for_html(q['question'])
        options = extract_options(q['question'])
        answer = extract_answer(q['question'])
        explanation = extract_explanation(q['question'])
        
        # 清理数据
        clean_options = []
        for option in options:
            # 移除多余的空白字符
            clean_option = re.sub(r'\s+', ' ', option.strip())
            clean_options.append(clean_option)
        
        quiz_items.append({
            'scenario': q['scenario'],
            'dimension': q['dimension'],
            'complexity': q.get('complexity', ''),  # 如果没有complexity字段则为空
            'question': escape_json_string(question_text.strip()),
            'options': [escape_json_string(opt) for opt in options],  # 确保只有4个选项
            'answer': answer,
            'explanation': escape_json_string(explanation.strip())
        })
    
    # 生成HTML内容
    html_content = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商业察言观色能力训练</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f4f7f9;
            color: #333;
            margin: 0;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        .quiz-container {
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            max-width: 800px;
            width: 100%;
            padding: 30px 40px;
            box-sizing: border-box;
        }
        .progress-bar {
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            margin-bottom: 20px;
            overflow: hidden;
        }
        .progress {
            height: 100%;
            background-color: #007bff;
            transition: width 0.3s ease;
        }
        .question-header {
            margin-bottom: 25px;
        }
        .question-header h1 {
            font-size: 1.6em;
            color: #0056b3;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        .question-header h2 {
            font-size: 1.2em;
            color: #495057;
            margin-bottom: 5px;
        }
        .question-header p {
            font-size: 1em;
            color: #6c757d;
            line-height: 1.6;
            white-space: pre-line;
        }
        .options-list {
            list-style: none;
            padding: 0;
        }
        .option-item {
            margin-bottom: 15px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
        }
        .option-item:hover {
            background-color: #f8f9fa;
            border-color: #adb5bd;
        }
        .option-item input[type="radio"] {
            margin-right: 15px;
            transform: scale(1.2);
        }
        .option-item label {
            cursor: pointer;
            font-size: 1em;
            flex-grow: 1;
            margin: 0;
        }
        .feedback {
            margin-top: 25px;
            padding: 20px;
            border-radius: 8px;
            display: none;
        }
        .feedback.correct {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .feedback.incorrect {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f1aeb5;
        }
        .feedback h3 {
            margin-top: 0;
            font-size: 1.3em;
        }
        .controls {
            margin-top: 30px;
            text-align: right;
        }
        .btn {
            padding: 12px 25px;
            font-size: 1em;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        .btn-primary:hover:not(:disabled) {
            background-color: #0056b3;
        }
        .btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>

<div class="quiz-container">
    <div class="progress-bar">
        <div class="progress" id="progressBar"></div>
    </div>

    <div id="questionContainer">
        <div class="question-header">
            <h1 id="questionTitle">加载中...</h1>
            <h2 id="questionSubtitle"></h2>
            <p id="questionDescription"></p>
        </div>

        <ul class="options-list" id="optionsList">
            <!-- Options will be inserted here by JavaScript -->
        </ul>

        <div id="feedbackArea" class="feedback">
            <h3 id="feedbackTitle"></h3>
            <p id="feedbackContent"></p>
        </div>

        <div class="controls">
            <button id="nextButton" class="btn btn-primary" onclick="loadNextQuestion()" disabled>下一题</button>
        </div>
    </div>
</div>

<script>
    const questionsData = ''' + json.dumps(quiz_items, ensure_ascii=False, indent=4) + ''';

    let currentQuestionIndex = 0;

    function loadQuestion(index) {
        const question = questionsData[index];
        const questionTitle = document.getElementById('questionTitle');
        const questionSubtitle = document.getElementById('questionSubtitle');
        const questionDescription = document.getElementById('questionDescription');
        const optionsList = document.getElementById('optionsList');
        const feedbackArea = document.getElementById('feedbackArea');
        const nextButton = document.getElementById('nextButton');
        const progressBar = document.getElementById('progressBar');

        questionTitle.textContent = question.dimension + ' - ' + question.scenario;
        questionSubtitle.textContent = '问题 ' + (index + 1) + ' / ' + questionsData.length;
        questionDescription.textContent = question.question;

        optionsList.innerHTML = '';
        question.options.forEach((option, i) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.innerHTML = `
                <input type="radio" id="option${i}" name="question" value="${String.fromCharCode(65 + i)}">
                <label for="option${i}">${option}</label>
            `;
            li.addEventListener('click', () => selectOption(String.fromCharCode(65 + i)));
            optionsList.appendChild(li);
        });

        feedbackArea.style.display = 'none';
        nextButton.disabled = true;

        const progressPercentage = ((index + 1) / questionsData.length) * 100;
        progressBar.style.width = `${progressPercentage}%`;
    }

    function selectOption(selectedValue) {
        const question = questionsData[currentQuestionIndex];
        const feedbackArea = document.getElementById('feedbackArea');
        const feedbackTitle = document.getElementById('feedbackTitle');
        const feedbackContent = document.getElementById('feedbackContent');
        const nextButton = document.getElementById('nextButton');
        const optionItems = document.querySelectorAll('.option-item');

        optionItems.forEach(item => {
            item.style.pointerEvents = 'none';
            const radio = item.querySelector('input[type="radio"]');
            if (radio.value === selectedValue) {
                if (selectedValue === question.answer) {
                    item.style.backgroundColor = '#d4edda';
                    item.style.borderColor = '#c3e6cb';
                } else {
                    item.style.backgroundColor = '#f8d7da';
                    item.style.borderColor = '#f1aeb5';
                }
            }
        });

        if (selectedValue === question.answer) {
            feedbackArea.className = 'feedback correct';
            feedbackTitle.textContent = '回答正确！';
        } else {
            feedbackArea.className = 'feedback incorrect';
            feedbackTitle.textContent = '回答错误。';
        }
        feedbackContent.textContent = question.explanation;
        feedbackArea.style.display = 'block';
        nextButton.disabled = false;
    }

    function loadNextQuestion() {
        currentQuestionIndex++;
        if (currentQuestionIndex < questionsData.length) {
            loadQuestion(currentQuestionIndex);
        } else {
            document.getElementById('questionContainer').innerHTML = `
                <h1>训练完成！</h1>
                <p>你已完成了所有题目，感谢参与本次商业察言观色能力训练。</p>
                <button class="btn btn-primary" onclick="location.reload()">重新开始</button>
            `;
        }
    }

    // Initial load
    loadQuestion(0);
</script>

</body>
</html>'''
    
    # 生成文件名
    date_str = datetime.now().strftime('%Y%m%d')
    filename = f'timu/quiz_{date_str}.html'
    
    # 确保timu目录存在
    os.makedirs('timu', exist_ok=True)
    
    # 写入文件
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    return filename

def main():
    """主函数"""
    # 加载题目库
    questions = load_questions()
    print(f"题库中共有 {len(questions)} 道题目")
    
    # 加载进度
    last_index = load_progress()
    print(f"上次使用到第 {last_index} 道题目")
    
    # 计算可使用的题目范围
    total_questions = len(questions)
    if last_index >= total_questions:
        print("题目已用完，从头开始")
        last_index = 0
    
    # 抽取20道题目
    selected_questions = []
    current_index = last_index
    
    for i in range(20):
        if current_index >= total_questions:
            current_index = 0  # 循环到开头
        
        selected_questions.append(questions[current_index])
        current_index += 1
    
    print(f"选中题目ID: {[q['id'] for q in selected_questions]}")
    
    # 生成测验HTML
    filename = generate_quiz_html(selected_questions)
    print(f"测验已生成: {filename}")
    
    # 保存进度
    save_progress(current_index)
    print(f"进度已保存: {current_index}")

if __name__ == "__main__":
    main()